﻿using cn.tozhang.linksms.data.Dto;
using Dapper;
using ExcelConfig;
using System;

namespace cn.tozhang.linksms.data
{
    public class MessageDB
    {
        internal IRepo repo;

        public MessageDB()
        {
            datainit.firewall.init_runner.OpenDBPort();
            datainit.db.init_runner.CreateDB();
            var connectstring = AppConfig.Text("数据库链接串");
            repo = new MysqlRepo(connectstring);
        }

        public void Run(string command)
        {
            repo.Open();

            using (var transaction = repo.Connection.BeginTransaction())
            {
                try
                {
                    repo.Connection.Execute(command, null, transaction);
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    // 发生异常时回滚事务
                    transaction.Rollback();
                    // 处理异常
                    Console.WriteLine(ex.Message);
                }
            }
        }
        public int Record(string? msg, string? from, string? to, DateTime time)
        {
            var lines = 0;
            var msg_item = new Message();
            msg_item.MsgID = Guid.NewGuid();
            msg_item.MsgFrom = from ?? string.Empty;
            msg_item.MsgTo = to??string.Empty;
            msg_item.MsgContent = msg?? string.Empty;
            msg_item.MsgTime = time;

            repo.Open();
            var exist = repo.Connection.QueryFirstOrDefault<bool>("select 1 from message where MsgFrom=@MsgFrom and MsgTime =@MsgTime", msg_item);

            if (!exist)
            using (var transaction = repo.Connection.BeginTransaction())
            {
                try
                {
                    lines += repo.Connection.Execute("insert into message (MsgID, MsgFrom, MsgTo, MsgName, MsgTime, MsgContent) values (@MsgID, @MsgFrom, @MsgTo, @MsgName, @MsgTime, @MsgContent);", msg_item, transaction);
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    // 发生异常时回滚事务
                    transaction.Rollback();
                    // 处理异常
                    Console.WriteLine(ex.Message);
                }
            }
            return lines;
        }
        public void Dispose()
        {
            repo.Dispose();
        }
    }
}
